package com.zhuss.util;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClient { 
	
	private static String url = "http://172.16.11.145:8098/weChat/order/createStirfry";
	
	private static String jsonString = "{\"expectFetchTimeStart\":1572796800000,\"expectFetchTimeEnd\":1572883200000, \"phone\":\"13800001111\",\"diningType\":10,\"comment\":\"我要吃好吃的2\",\"userId\":51,\"stirfryList\":[{\"productId\":15044,\"productNo\":\"PRODUCT_20190902185216462\",\"category\":10,\"name\":\"特价包子\",\"date\":null,\"status\":null,\"price\":1000,\"picUrl\":\"XXX\",\"count\":3}]}";
	
	public static void main(String[] args) throws Exception {
		
		long start = System.currentTimeMillis();
		
			new Runnable() {
				@Override
				public void run() {
					try {
						Object response = query(url, jsonString);
						System.out.println(response);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.run();
		
		long end = System.currentTimeMillis();
		
		System.out.println("==============" + (end - start));
	}
	
	
	/**
     * 查询指定gift的文件
     *
     * @param key
     * @param url
	 * @return 
     * @return
     * @throws Exception
     */
    public static Object query(String url, String jsonString) throws Exception {
        CloseableHttpClient hc = null;
        try {
            hc = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            
            HttpEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
            post.setEntity(entity);  
            
            HttpResponse response = hc.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception();
            }

            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity);

            @SuppressWarnings("unchecked")
            Map<String, Object> resultMap = JsonUtil.fromJson(result, Map.class);
            if (resultMap == null || resultMap.size() == 0) {
                throw new Exception();
            }
            
            return resultMap.get("response");

        } catch (Exception e) {
            throw new Exception();
        } finally {
            try {
                if (hc != null) {
                    hc.close();
                }
            } catch (Exception e2) {
            }
        }
    }
}
